#include <fstream>
#include <string>
#include <filesystem>

#include "page.h"
#include "exception.h"
#include "subprojects/tedi2html/tedi2html.h"
using namespace std;
using namespace filesystem;
page::~page(){}
page::page(){}
/*
 * part_path: part file with tedi code
 * header: complete header text from header file
 * end: complete header text from end file
 */
page::page(string part_path, string header, string end){
 this->header = header;
 this->path = part_path;

 string part;
 ifstream reader(part_path);
 string line;
 while(getline(reader,line))
	 part += line + "\n";
 reader.close();

 this->body = part;
 this->end = end;

}

page& page::operator =(const page& P)
{
	if (this != &P) { // avoid self-allocation
		path = P.path;
		header = P.header;
		body = P.body;
		end = P.end;
	}
	return *this;
}

void page::save(){
	string current_folder = current_path();
	cout << current_folder + "/www" + path.substr(current_folder.size() + 6) + ".html" << endl;
	ofstream writer(current_folder + "/www" + path.substr(current_folder.size() + 6) + ".html");
	string text;
	try{
		text = tedi2html().convert(body, header, end);
	}catch(Invalid i){
		cout << i.line() << endl;
		cout << i.reason() << endl;
	}
	writer << text;
	writer.close();
}
